package Engine.loader;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Vector;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

import Engine.loader.obj.Face;
import Engine.loader.obj.Group;
import Engine.loader.obj.ModelObj;
import Engine.loader.obj.Vertex;
import Engine.loader.obj.VertexNormal;
import Engine.loader.obj.VertexTexture;

public class Loader {

	private int line = 1;
	private String strLine;
	private String texturePath;
	
	public void OBJ(String filePath, Vector<ModelObj> modelList, String texturePath) {
		long init = System.currentTimeMillis();
		this.texturePath = texturePath;
		System.out.println("Loader.OBJ()");
		try {
			// Open the file that is the first
			// command line parameter
			FileInputStream fstream = new FileInputStream(new File(filePath));
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));

			ModelObj modelObj = new ModelObj(texturePath);

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				decode(strLine, modelList, modelObj);
				line++;
			}
			// Close the input stream
			in.close();
		} catch (Exception e) {
			System.err.println("Error line "+ line + " : " + e + "\n" + strLine);
		}
		System.out.println("Read obj took:  "
				+ String.valueOf(System.currentTimeMillis() - init) + " msec "
				+ "objects in file: " + modelList.size());
	}

	private void decode(String strLine,
			Vector<ModelObj> modelList, ModelObj modelObj) {
		if (strLine.contains("# ")) {
			return;
		}

		if (strLine.contains("v ")) {
			modelObj.vertex.add(new Vertex(strLine));
		}

		if (strLine.contains("vn ")) {
			modelObj.vertexNormal.add(new VertexNormal(strLine));
		}

		if (strLine.contains("vt ")) {
			modelObj.vertexTexture.add(new VertexTexture(strLine));
		}

		if (strLine.contains("g ")) {
			modelObj.groupId = new String(strLine.replace("g ", "")); 
		}

		if (strLine.contains("usemtl ")) {
			modelObj.materialId = strLine.replace("usemtl ", "");
		}

		if (strLine.contains("f ")) {
			modelObj.face.add(new Face(strLine));
			modelObj.lastFace = modelObj.face.size()-1;
		}

		if (strLine.contains("endg")) {
			modelList.add(new ModelObj(modelObj));
			
			modelObj.firstFace = modelObj.face.size();
//			modelObj.face.clear();
//			modelObj.vertex.clear();
//			modelObj.vertexNormal.clear();
//			modelObj.vertexTexture.clear();
		}
	}
}
